package Netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * Created by brossdong on 2017/12/11.
 */
public class Server {

    public static void main(String[] args) throws Exception {
        //第一个线程组用于接收client端连接的
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //第二个线程组用于实际业务处理的
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //new一个启动nio的辅助类
            //对server进行配置
            ServerBootstrap b = new ServerBootstrap();
            //绑定线程组
            b.group(bossGroup,workerGroup)
             //指定使用NioServerSocketChannel的通道----tcp的
             .channel(NioServerSocketChannel.class)
             //绑定具体的 事件处理器
             .childHandler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 protected void initChannel(SocketChannel sc) throws Exception {
                     //设置特殊分隔符
                     ByteBuf byteBuf = Unpooled.copiedBuffer("$_".getBytes());
                     sc.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,byteBuf));
                     //设置字符串形式解码
                     sc.pipeline().addLast(new StringDecoder());

                     sc.pipeline().addLast(new ServerHandler());
                 }
             })
             //设置tcp缓冲区
             .option(ChannelOption.SO_BACKLOG, 128)
             //保持连接
             .childOption(ChannelOption.SO_KEEPALIVE, true);

            //指定端口进行监听
            ChannelFuture f = b.bind(8765).sync();
            //ChannelFuture f1 = b.bind(8764).sync();

            //进行阻塞
            //类似于Thread.sleep(20000);
            f.channel().closeFuture().sync();
            //f1.channel().closeFuture().sync();

        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

}
